import { Component, OnInit } from '@angular/core';
import { NzModalService, NzMessageService } from 'ng-zorro-antd';
import { _HttpClient } from '@core/services/http.client';
import { Observable } from 'rxjs/Observable';
import {Router} from '@angular/router';
import * as moment from 'moment';
import {TokenData} from "@core/net/token/token.type";
import {HttpService} from "@core/services/http.service";

import {
    FormBuilder,
    FormGroup,
    Validators,
    FormControl
} from '@angular/forms';
import {TokenService} from "@core/net/token/token.service";

declare var jsPlumb:any;
@Component({
    selector: 'app-user',
    templateUrl: './user.component.html',
    styles  : [ `
    :host ::ng-deep .vertical-center-modal {
      display: flex;
      align-items: center;
      justify-content: center;
    }

    :host ::ng-deep .vertical-center-modal .ant-modal {
      top: 0; 
    }
  ` ]

})
export class UserComponent implements OnInit {
    validateForm: FormGroup;
    q: any = {
        pi: 1,
        ps: 10,
        sorter: '',
        status: -1,
        statusList: []
    };
    username: any;
    data: any[] = [];
    loading = false;
    selectedRows: any[] = [];
    curRows: any[] = [];
    totalCallNo = 0;
    allChecked = false;
    indeterminate = false;
    isupdate=0;
    status = [

        { text: '项目设计员', value: false, type: 'processing' },
        { text: '院校管理员', value: false, type: 'success' }
        // { text: '异常', value: false, type: 'error' }
    ];
    sortMap: any = {};
    expandForm = false;
    modalVisible = false;
    description = '';
    radioValue='';
    U_name: any;
    U_pwd: any;
    U_email: any;
    U_phone: any;
    U_remark: any;
    LoginName: any;
    selectid:any;
    jsflag=false;
    yxflag=false;
    xmflag=false;
    _value: any;
    ngAfterViewInit() {
        let me = this;
        jsPlumb.ready(function() {
            // alert(1)
            // jsPlumb.addEndpoint(me.testEl.nativeElement);
        });
    }
    constructor(public msg: NzMessageService,private http: HttpService ,private fb: FormBuilder , private confirmServ: NzModalService, private msgService: NzMessageService,private token:TokenService ) {}

    ngOnInit() {
        this._value='';
        this.flags();
        this.validateForm = this.fb.group({
            U_name         : [ null, [ Validators.required ] ],
            U_pwd         : [ null, [ Validators.required ] ],
            U_email            : [ null, [ Validators.required ] ],
            LoginName            : [ null, [ Validators.required ] ],
            radioValue       : [  null, [ Validators.required ]  ]
        });
        this.getData();




    }

    flags(){

        var role = this.token.data.role;
        if(role==2){this.yxflag=true;this.xmflag=true;}//院校管理员
        if(role==3){this.jsflag=true;}
        //if(role==2){}


    }

    getFormControl(name) {
        return this.validateForm.controls[ name ];
    }

    _submitForm() {

        // tslint:disable-next-line:forin
        // for (const i in this.validateForm.controls) {
        //     this.validateForm.controls[i].markAsDirty();
        // }


    }

    getData() {

        // this.pageChange(1).then(() => {
        //     this.q.statusList = this.status.map((i, index) => i.value ? index : -1).filter(w => w !== -1);
        //     if (this.q.status && this.q.status > -1) this.q.statusList.push(this.q.status);
        //   //  console.log(this.q);
        //     this.data = getRule(this.q).map(i => {
        //         const statusItem = this.status[i.status];
        //         i.statusText = statusItem.text;
        //         i.statusType = statusItem.type;
        //         return i;
        //     });
        //
        // });


        const  obj = {
            State: '0',
            Role:this.token.data.role,
            Condition:this._value

        };
        this.http.userList(obj).subscribe(res => {
            if (res['code'] == '0') {
                this.data=res['list'];
                this.loading = false;
            } else {
                this.msgService.error(res['msg'])
                this.data =[];
                this.loading = false;
            }
        });




    }

    add() {
        this.modalVisible = true;


    }

    search() {

        this.getData();

    }
    show(modalContent,obj) {




        this.U_name =obj.UserName;
        this.U_pwd=obj.LoginPwd;
        this.U_email =obj.ContactWay;
        this.radioValue = obj.type;
        this.LoginName =obj.LoginName;


      // this.U_name.nzDisabled = true;
       //  this.U_name.nzReadonly =true;
       //  this.U_pwd.nzReadonly=true;
       //  this.U_email.nzReadonly =true;
       // // this.radioValue.nzDisabled = true;
       //  this.LoginName.nzReadonly =true;

        this.confirmServ.info({
            title: '查看详情',
            content: modalContent,
            okText: '确定'
        });

    }
    edit(obj) {
        this.U_name =obj.UserName;
        this.U_pwd=obj.LoginPwd;
        this.U_email =obj.ContactWay;
        this.radioValue = obj.RoleType.toString();
        this.LoginName =obj.LoginName;
        this.selectid=obj.id;
        this.isupdate = 1;
        this.modalVisible = true;
    }
    del(val) {
        let context =this;

        this.confirmServ.confirm({
            title  : '您是否确认要删除这项内容',
            content: '',
            okText:'确定',
            cancelText:'取消',
            onOk() {
                const obj = {
                    id: val.toString()
                };
                context.http.userDel(obj).subscribe(res => {
                    if (res['code'] == '0') {
                        context.msgService.success(res['msg'])
                       context.getData()
                        context=null;

                    } else {
                        context.msgService.error(res['msg'])
                    }
                });


            },
            onCancel() {
            }
        });



    }
    test(res){

    }
    save() {

        if(this.isupdate==1){
            //修改
            var   obj = {
                LoginName: this.U_name ,
                LoginPwd: this.U_pwd ,
                ContactWay: this. U_email ,
                Type: this.radioValue ,
                UserName: this.U_name,
                id:  this.selectid.toString()
            };
            if (this.validateForm.valid) {
                this.http.userUpdate(obj).subscribe(res => {
                    if (res['code'] == '0') {
                        this.msgService.success(res['msg'])
                        this.getData();
                        this.modalVisible = false;
                        this.clear();
                    } else {
                        this.msgService.error(res['msg'])
                    }
                });

                //this.modalVisible = false;
            } else {
                this.msg.error('请输入完整内容后再保存！');
            }


        }else{
            const  obj = {
                LoginName: this.U_name ,
                LoginPwd: this.U_pwd ,
                ContactWay: this. U_email ,
                Type: this.radioValue ,
                UserName: this.U_name

            };
            if (this.validateForm.valid) {
                this.http.userAdd(obj).subscribe(res => {
                    if (res['code'] == '0') {
                        this.msgService.success(res['msg'])
                        this.getData();
                        this.clear();
                    } else {
                        this.msgService.error(res['msg'])
                    }
                });

                this.modalVisible = false;
            } else {
                this.msg.error('请输入完整内容后再保存！');
            }


        }



    }

    remove() {

        let context =this;
        var str="";
        this.curRows.forEach(i => {
            if(  i.checked)
            {
                str+=i.id + ",";
            }
        });
        str=(str.substring(str.length-1)==',')?str.substring(0,str.length-1):str;
        this.confirmServ.confirm({
            title  : '您是否确认要删除'+this.selectedRows.length+'项内容',
            content: '',
            okText:'确定',
            cancelText:'取消',
            onOk() {
                const  obj = {
                    id: str.toString()
                };
                context.http.userDel(obj).subscribe(res => {
                    if (res['code'] == '0') {
                        context.msgService.success(res['msg'])
                        context.getData();
                        context=null;
                    } else {
                        context.msgService.error(res['msg'])
                    }
                });
            },
            onCancel() {
            }
        });






    }

    approval() {
        this.msg.success(`审批了 ${this.selectedRows.length} 笔`);
    }

    clear() {
        this.selectedRows = [];
        this.totalCallNo = 0;
        this.data.forEach(i => i.checked = false);
        this.refreshStatus();
        this.description = '';
        this.radioValue='';
        this.U_name='';
        this.U_pwd='';
        this.U_email='';
        this.U_phone='';
        this.U_remark='';
        this.LoginName='';
    }

    checkAll(value: boolean) {
        this.curRows.forEach(i => {
            if (!i.disabled) i.checked = value;
        });
        this.refreshStatus();
    }

    refreshStatus() {
        const allChecked = this.curRows.every(value => value.disabled || value.checked);
        const allUnChecked = this.curRows.every(value => value.disabled || !value.checked);
        this.allChecked = allChecked;
        this.indeterminate = (!allChecked) && (!allUnChecked);
        this.selectedRows = this.data.filter(value => value.checked);
        this.totalCallNo = this.selectedRows.reduce((total, cv) => total + cv.callNo, 0);
    }

    sort(field: string, value: any) {
        this.sortMap = {};
        this.sortMap[field] = value;
        this.q.sorter = value ? `${field}_${value}` : '';
        this.getData();
    }

    dataChange(res: any) {

        this.curRows = res;
        this.refreshStatus();
    }

    pageChange(pi: number): Promise<any> {
        this.q.pi = pi;
        this.loading = true;
        return new Promise((resolve) => {
            setTimeout(() => {
                this.loading = false;
                resolve();
            }, 500);
        });
    }

    reset(ls: any[]) {
        for (const item of ls) item.value = false;
        this.getData();
    }
}
